package com.gitee.simons.common.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: jsm
 * @date: 2018/11/19 09:09
 */
@Data
@AllArgsConstructor
@Slf4j
public class JsonResult<T> {
    private Boolean success = true;
    private String msg = "";
    private T data = null;
    private Integer errorCode = null;

    /**
     * 登录异常码
     */
    public static final int LOGIN_ERROR_CODE = 521;

    /**
     * 普通异常码
     */
    public static final int SIMPLE_ERROR_CODE = 520;

    /**
     * 成功时的msg
     */
    private static final String SUCCESS_CODE = "操作成功";

    public JsonResult() {
        this.success = true;
    }

    public JsonResult(Boolean success, String msg) {
        this.success = success;
        this.msg = msg;
    }

    public JsonResult(Boolean success) {
        this.success = success;
    }

    public void setData(T data) {
        this.data = data;
        if (data == null && StringUtils.isEmpty(this.msg)) {
            this.msg = "查询/执行 -> 失败/无数据";
        } else if (data instanceof String && StringUtils.isEmpty(String.valueOf(data))) {
            this.msg = "查询/执行 -> 失败/无数据";
        }

    }

    public static JsonResult success() {
        return new JsonResult(true, SUCCESS_CODE);
    }

    public JsonResult success(T data) {
        return new JsonResult(true, SUCCESS_CODE, data, null);
    };

    public static JsonResult fail(String msg) {
        return fail(msg, SIMPLE_ERROR_CODE);
    }

    public static JsonResult fail(String msg, Integer errorCode) {
        JsonResult<String> jsonResult = new JsonResult(false, msg);
        jsonResult.setErrorCode(errorCode);
        return jsonResult;
    }
}
